package vn.student;

import java.util.ArrayList;
import vn.student.controller.ViewAssignmentDetailController;
import vn.student.mylib.Constants;
import vn.student.mylib.Contact;
import vn.student.mylib.DateDialog;
import vn.student.mylib.DateTimeDialog;
import vn.student.mylib.ListContactAdapter;
import vn.student.mylib.ListPriorityAdapter;
import vn.student.mylib.TextInputDialog;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;
	
public class ViewAssignmentDetail extends Activity implements View.OnClickListener{
	boolean isEdit = false;
	String id=null;
	Activity act = this;
	AlertDialog chooseTypeDialog = null;
	ViewAssignmentDetailController controller = null;
	boolean isCreateNew = false;
	boolean isEditSomething = false;
	
	/*
		Method name: public void onCreate(Bundle savedInstanceState).
		Function: Duoc chay dau tien khi Activity duoc mo len. Ham co tac dung lay ve thong tin chi tiet
			cua mot bai tap (Assignment) va the hien len GUI. Ngoai ra phuong thuc con gan cac su kien cho 
			mot so nut duoc dung tren man hinh hien thi.
		Parameter: Bundle savedInstanceState: Nhung thong tin duoc luu lai truoc khi Activity 
			chuyen tu trang thai Running qua Plaused.
		Return: None.
		Note:
    */
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.assignment_detail);
		Intent intent = this.getIntent();
		id = intent.getExtras().getString("id");
		this.isEdit = intent.getExtras().getBoolean("isEdit");
		this.isCreateNew = intent.getExtras().getBoolean("isCreateNew");
		String classId = intent.getExtras().getString("classId");
		this.id = id;
		controller = new ViewAssignmentDetailController(this,id,isCreateNew,classId);
		// Neu Activity duoc mo de chinh sua thong tin chi tiet thi chuyen qua Edit Mode.
		if(isEdit)
			changeTextViewToEditState();
		// Gan su kien cho cac nut chinh tren giao dien hien thi thong tin mon hoc.
		RelativeLayout tmp = (RelativeLayout) findViewById(R.id.button01);
		tmp.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if(isEdit)
					onClickCancelButton();
				else
					onClickBackButton();
			}
		});
		tmp = (RelativeLayout) findViewById(R.id.button02);
		tmp.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if(isEdit)
					onClickSaveButton();
				else
					onClickEditButton();
			}
		}); 
		tmp = (RelativeLayout) findViewById(R.id.editAssNameBtn);
		tmp.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if(!isEdit)
					return;
				TextInputDialog.viewDialog("Input course name",controller.assignmentInfo.name, act, new InputTextDialogOnOkClickListener());
			}
		});
		
		tmp = (RelativeLayout) findViewById(R.id.editDueDateBtn);
		tmp.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if(!isEdit)
					return;
				DateDialog.viewDialog("Due date",act,controller.assignmentInfo.dueDate.split("-"), new DateDialogOnOkClickListener());
			}
		});
		
		tmp = (RelativeLayout) findViewById(R.id.editAlertTimeBtn);
		tmp.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if(!isEdit)
					return;
				DateTimeDialog.viewDialog("Alert time",act, new DateTimeDialogOnOkClickListener());
			}
		}); 
		
		tmp = (RelativeLayout) findViewById(R.id.editPriorityBtn);
		tmp.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if(!isEdit)
					return;
				editPriority();
			}
		}); 
		
		tmp = (RelativeLayout) findViewById(R.id.editContentBtn);
		tmp.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if(!isEdit)
					return;
				editDescription();
			}
		}); 
		if(!isCreateNew){
			tmp = (RelativeLayout) findViewById(R.id.addPartnerBtn);
			tmp.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					addPartner();
				}
			}); 
			
			tmp = (RelativeLayout) findViewById(R.id.deleteAssignmentBtn);
			tmp.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					if(!isEdit)
						return;
					controller.deleteAssignment();
					act.setResult(RESULT_OK);
					act.finish();
				}
			}); 
		}
		else{
			tmp = (RelativeLayout) findViewById(R.id.deleteAssignmentBtn);
			tmp.setVisibility(View.INVISIBLE);
			tmp = (RelativeLayout) findViewById(R.id.addPartnerBtn);
			tmp.setVisibility(View.INVISIBLE);
		}
		

		ImageButton imgBtn = (ImageButton) act.findViewById(R.id.isDoneBtn);
		imgBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				isEditSomething = true;
				controller.editDone();
			}
		}); 
		
		controller.showAssDetail();
	}
	/*
		Method name: private void editDescription().
		Function: Ham duoc goi khi user nhan nut edit description. Phuong thuc co tac dung khoi tao 1 Dialog cho phep 
			nhap description cho bai tap.
		Parameter: None.
		Return: None.
		Note:
    */
	private void editDescription(){
		if(!isEdit)
			return;
		TextInputDialog.viewDialog("Input assignment description",controller.assignmentInfo.des, act, new InputText2DialogOnOkClickListener());
	}
	/*
		Method name: private void editPriority().
		Function: Ham duoc goi khi user nhan nut edit priority. Phuong thuc co tac dung khoi tao 1 Dialog cho phep 
			chon do uu tien (priority) cho bai tap.
		Parameter: None.
		Return: None.
		Note:
    */
	private void editPriority(){
		LayoutInflater li = LayoutInflater.from(act); 
		View view = li.inflate(R.layout.priority_list_view, null); 
		AlertDialog.Builder builder = new AlertDialog.Builder(act); 
		builder.setTitle("Choose Priority"); 
		builder.setView(view);
		builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// Khong thuc hien gi ca. Don gian dong Dialog khi nguoi dung nhan "Cancel"
			}
		});
		ArrayList<String> pri = new ArrayList<String>();
		pri.add("High");
		pri.add("Normal");
		pri.add("Low");
		ListView listPartnerView = (ListView) view.findViewById(R.id.priorityListView);
		listPartnerView.setAdapter(new ListPriorityAdapter(act,view, pri));
		listPartnerView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				controller.editPriority(arg2);
				chooseTypeDialog.dismiss();
				chooseTypeDialog = null;
			}
		});
		//get the dialog 
		chooseTypeDialog = builder.create();
		// Hien thi Dialog
		chooseTypeDialog.show();
	}
	/*
		Method name: private void onClickCancelButton().
		Function: Phuong thuc duoc goi khi user nhan nut Cancel tren man hinh chinh. Phuong thuc co tac dung 
			chuyen Activity tu Edit Mode ve View Mode.
		Parameter: None.
		Return: None.
		Note:
    */
	private void onClickCancelButton(){
		isEdit = false;
		if(isCreateNew){
			this.setResult(RESULT_CANCELED);
		}
		changeTextViewEditStateToView();
	}
	/*
		Method name: private void onClickSaveButton().
		Function: Phuong thuc duoc goi khi user nhan nut Save tren man hinh chinh. Phuong thuc co tac dung 
			chuyen Activity tu Edit Mode ve View Mode va luu thong tin chi tiet bai tap moi chinh sua vao CSDL.
		Parameter: None.
		Return: None.
		Note:
    */
	private void onClickSaveButton(){
		isEdit = false;
		isEditSomething = true;
		// Neu la tao moi Ass thi them moi 1 Ass vao CSDL, nguoc lai thi cap nhap Ass trong CSDL.
		if(isCreateNew){
			this.setResult(RESULT_OK);
			controller.addNewAssignment();
			this.finish();
		}
		else
			controller.updateAssignment();
		changeTextViewEditStateToView();	
	}
	/*
		Method name: private void addPartner().
		Function: Phuong thuc duoc goi khi user nhan nut "Add Partner" tren man hinh chinh. Phuong thuc co tac dung 
			mo ra 1 Dialog liet ke danh sach sinh vien de nguoi dung chon them vao danh sach partner.
		Parameter: None.
		Return: None.
		Note:
    */
	private void addPartner(){
		LayoutInflater li = LayoutInflater.from(act); 
		// Tao doi tuong View (Chinh la GUI hien thi danh sach sinh vien de chon partner) va load giao dien tu file XML.
		View view = li.inflate(R.layout.instructor_list_view, null); 
		AlertDialog.Builder builder = new AlertDialog.Builder(act); 
		builder.setTitle("Choose Partner"); 
		builder.setView(view); 
		// Gan su kien cho nut "Add new Partner".
		builder.setPositiveButton("Add new Partner", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				addNewPartner();
			}
		});
		builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// KHong lam gi ca. Don gian la dong Dialog.
			}
		});
		// Lay danh sach sinh vien co the them vao danh sach Partner.
		ArrayList<Contact> studetnList = controller.getPartner();
		// Load ListView tu giao dien de gan danh sach sinh vien.
		ListView listPartnerView = (ListView) view.findViewById(R.id.contactListView);
		listPartnerView.setAdapter(new ListContactAdapter(this,view,studetnList));
		// Gan doi tuong Listener su ly su kien nhan vao moi Item trong danh sach sinh vien cos the chon lam partner.
		listPartnerView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				ListContactAdapter adapter = (ListContactAdapter) arg0.getAdapter();
				ArrayList<Contact> list = adapter.list;
				Contact contact = list.get(arg2);
				// Them student vao danh sach partner.
				controller.addPartner(list.get(arg2).id);
				chooseTypeDialog.dismiss();
				chooseTypeDialog = null;
				
				ListView listView = (ListView) findViewById(R.id.contactListView);
          	  	ArrayList<Contact> listPartner = (ArrayList<Contact>)((ListContactAdapter)listView.getAdapter()).list;
				listPartner.add(contact);
				listView.setAdapter(new ListContactAdapter(act,listPartner));
			}
		});
		//}
		//Tao va hien thi Dialog.
		chooseTypeDialog = builder.create();
		chooseTypeDialog.show();
	}
	private void changeTextViewToEditState(){
		TextView txtView = (TextView)this.findViewById(R.id.tv01);
		txtView.setText("Cancel");
		txtView = (TextView)this.findViewById(R.id.tv03);
		txtView.setText("Save");
		RelativeLayout rl = (RelativeLayout) this.findViewById(R.id.deleteAssignmentBtn);
		rl.setVisibility(View.VISIBLE);
		txtView = (TextView)this.findViewById(R.id.editBtn01);
		txtView.setVisibility(View.VISIBLE);
		txtView = (TextView)this.findViewById(R.id.editBtn02);
		txtView.setVisibility(View.VISIBLE);
		txtView = (TextView)this.findViewById(R.id.editBtn03);
		txtView.setVisibility(View.VISIBLE);
		txtView = (TextView)this.findViewById(R.id.editBtn04);
		txtView.setVisibility(View.VISIBLE);
		txtView = (TextView)this.findViewById(R.id.editBtn05);
		txtView.setVisibility(View.VISIBLE);
	}
	private void changeTextViewEditStateToView(){
		TextView txtView = (TextView)this.findViewById(R.id.tv01);
		txtView.setText("Back");
		txtView = (TextView)this.findViewById(R.id.tv03);
		txtView.setText("Edit");
		RelativeLayout rl = (RelativeLayout) this.findViewById(R.id.deleteAssignmentBtn);
		rl.setVisibility(View.INVISIBLE);
		txtView = (TextView)this.findViewById(R.id.editBtn01);
		txtView.setVisibility(View.INVISIBLE);
		txtView = (TextView)this.findViewById(R.id.editBtn02);
		txtView.setVisibility(View.INVISIBLE);
		txtView = (TextView)this.findViewById(R.id.editBtn03);
		txtView.setVisibility(View.INVISIBLE);
		txtView = (TextView)this.findViewById(R.id.editBtn04);
		txtView.setVisibility(View.INVISIBLE);
		txtView = (TextView)this.findViewById(R.id.editBtn05);
		txtView.setVisibility(View.INVISIBLE);
	}
	private void addNewPartner(){
		Intent intent = new Intent(act,ViewContactDetail.class);
		Bundle bundle = new Bundle();
		bundle.putString("id","-1");
		bundle.putBoolean("isEdit", true);
		bundle.putBoolean("isInstructor", false);
		bundle.putBoolean("isCreateNew", true);
		intent.putExtras(bundle);
		act.startActivityForResult(intent,Constants.VIEW_ADD_NEW_PARTNER_EDITOR);
	}
	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		
	}
	public void onClickBackButton(){
		if(isEditSomething)
			this.setResult(RESULT_OK);
		else
			this.setResult(RESULT_CANCELED);
		this.finish();
	}
	public void onClickEditButton(){
		isEdit = true;
		changeTextViewToEditState();
	}
	 @Override
	public boolean onContextItemSelected(MenuItem  aItem) {
	   	AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) aItem.getMenuInfo();
	        /* Switch on the ID of the item, to get what the user selected. */
	        switch (aItem.getItemId()) {
	        	case Constants.ASS_CONTEXTMENU_ADDPARTNER:
	         	{	
	         		addPartner();
	         		//addNewPartner();
					return true;
	         	}
	              case Constants.ASS_CONTEXTMENU_DELETEITEM:
	              {
	            	  ListView listView = (ListView) findViewById(R.id.contactListView);
	              	  Contact contact = ((ListContactAdapter)listView.getAdapter()).list.get(menuInfo.position);
	              	  ListContactAdapter adapter = (ListContactAdapter)listView.getAdapter();
	            	  ArrayList<Contact> tmp = adapter.list;
	            	  if(controller.removePartner(contact.id)){
	            		  tmp.remove(contact);
	            		  adapter.list = tmp;
	            		  if(tmp!=null&&tmp.size()==0){
	            			  ((RelativeLayout) act.findViewById(R.id.addPartnerBtn)).setBackgroundResource(R.drawable.class_row_all);
	            		  }
	            			  
	            		  listView.setAdapter(adapter);
	            		  
	            	  }
	            	  else{
	            		  // Do something...
	            	  }
	              }
	              return true;
	         }
	         return false;
	    }
	class DateTimeDialogOnOkClickListener implements android.content.DialogInterface.OnClickListener {

		@Override
		public void onClick(DialogInterface dialog, int which) {
			DatePicker date = (DatePicker) ((AlertDialog)dialog).findViewById(R.id.datePicker);
			String dateStr = String.valueOf(date.getYear())+"-"+String.valueOf(date.getMonth())+"-"+String.valueOf(date.getDayOfMonth());
			TimePicker time = (TimePicker) ((AlertDialog)dialog).findViewById(R.id.timePicker);
			String timeStr = String.valueOf(time.getCurrentHour())+":"+String.valueOf(time.getCurrentMinute())+":00";
			controller.editAlertTime(dateStr,timeStr);
		}
		
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode,Intent data) {
	    if (requestCode==Constants.VIEW_ADD_NEW_PARTNER_EDITOR) {
		      if (resultCode==RESULT_OK) {
		    	  String partnerId = data.getExtras().getString("studentId");
		    	  String partnerName = data.getExtras().getString("studentName");
		    	  controller.addPartner(partnerId);
		    	  ListView listView = (ListView) findViewById(R.id.contactListView);
		    	  ArrayList<Contact> listPartner = (ArrayList<Contact>)((ListContactAdapter)listView.getAdapter()).list;
		    	  listPartner.add(new Contact(partnerId,partnerName));
		    	  listView.setAdapter(new ListContactAdapter(act,listPartner));
		      }
	    }
	  }
	class DateDialogOnOkClickListener implements android.content.DialogInterface.OnClickListener {

		@Override
		public void onClick(DialogInterface dialog, int which) {
			DatePicker date = (DatePicker) ((AlertDialog)dialog).findViewById(R.id.datePicker);
			String dateStr = "";
			String tmp = "";
			dateStr = String.valueOf(date.getYear()) + "-";
			tmp = String.valueOf(date.getMonth()+1);
			tmp = tmp.length()==2?tmp:("0"+tmp);
			dateStr += tmp + "-";
			tmp = String.valueOf(date.getDayOfMonth());
			tmp = tmp.length()==2?tmp:("0"+tmp);
			dateStr += tmp;
			controller.editDueDate(dateStr);
		}
	}
	class InputTextDialogOnOkClickListener implements android.content.DialogInterface.OnClickListener {

		@Override
		public void onClick(DialogInterface dialog, int which) {
			String name = ((EditText) ((Dialog) dialog).findViewById(R.id.editTextView)).getText().toString();
			controller.editAssName(name);
		}
	}
	class InputText2DialogOnOkClickListener implements android.content.DialogInterface.OnClickListener {

		@Override
		public void onClick(DialogInterface dialog, int which) {
			String des = ((EditText) ((Dialog) dialog).findViewById(R.id.editTextView)).getText().toString();
			controller.editDesName(des);
		}
	}
}
